package com.whadee.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whadee.demo.domain.dto.UserRegisterDTO;
import com.whadee.demo.domain.dto.UserLoginDTO;
import com.whadee.demo.domain.po.User;
import com.whadee.demo.domain.query.UserPageQuery;
import com.whadee.demo.domain.vo.PageVo;
import com.whadee.demo.exception.BusinessException;
import com.whadee.demo.mapper.UserMapper;
import com.whadee.demo.result.ResponseEnum;
import com.whadee.demo.result.ResponseVo;
import com.whadee.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whadee.demo.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import com.whadee.demo.utils.RandomUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author novel
 * @since 2024-08-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseVo register(UserRegisterDTO registerDTO) {
        if (registerDTO.getName()==null) {
            throw new BusinessException(ResponseEnum.REGISTER_FAIL);
        }
        User user = new User();
        //拷贝值
        BeanUtils.copyProperties(registerDTO,user);

        user.setSecret("$1$"+ RandomUtils.getStringNumRandom(6));

        //密码+盐 加密处理
        String pwd = Md5Crypt.md5Crypt(registerDTO.getPwd().getBytes(), user.getSecret());
        user.setPwd(pwd);

        //账号唯一性检查 123456@qq.com
        if (checkUnique(user.getEmail())) {
            //保存用户信息
            userMapper.insert(user);
            return ResponseVo.ok().message("注册成功");
        }else {
            //用户已经存在
            return ResponseVo.setResult(ResponseEnum.USER_REPEAT);
        }
    }

    @Override
    public ResponseVo login(UserLoginDTO userLoginDTO) {
        List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("email", userLoginDTO.getEmail()));
        if (userList != null && userList.size() ==1) {
            //验证通过
            User user = userList.get(0);
            //对请求过来的密码进行加密
            String crypt = Md5Crypt.md5Crypt(userLoginDTO.getPwd().getBytes(), user.getSecret());
            if (crypt.equals(user.getPwd())) {
                String token = JWTUtil.geneJsonWebToken(user);
                return ResponseVo.ok().data("token",token);
            }else {
                return ResponseVo.setResult(ResponseEnum.USER_PWD_ERROR);
            }
        }else {
            //未注册
            return ResponseVo.setResult(ResponseEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public ResponseVo queryUserPage(UserPageQuery pageQuery) {
        Page<User> sort = pageQuery.toMpPageDefaultSortByCreateTimeDesc();
        String age = pageQuery.getAge();
        Page<User> page = lambdaQuery().eq(Objects.nonNull(age),User::getAge,age)
                .eq(StringUtils.isNotBlank(pageQuery.getEmail()),User::getEmail,pageQuery.getEmail())
                .page(sort);
        PageVo<User> userPageVo = new PageVo<>();
        userPageVo.of(page);
        return ResponseVo.ok().data("items",userPageVo);

    }

    /**
     * 校验用户账号唯一
     * @param email
     * @return
     */
    private boolean checkUnique(String email) {

        QueryWrapper queryWrapper = new QueryWrapper<User>().eq("email", email);

        //查找数据库中是否有对应的账号
        List<User> list = userMapper.selectList(queryWrapper);
        //大于零返回false否则返回true
        return list.size() > 0 ? false : true;

    }
}
